package sketchpad.gui.component;

import com.jfoenix.animation.alert.JFXAlertAnimation;
import com.jfoenix.controls.JFXAlert;
import com.jfoenix.controls.JFXDialogLayout;
import javafx.scene.control.Label;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import sketchpad.constant.Config;
import sketchpad.gui.control.DrawControl;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

public class FileExplorer {
    private FileChooser fileChooser;
    public FileExplorer(){
        fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("画板文件", "*."+Config.FILE_SUFFIX),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );
    }

    public void openFile(Stage stage, DrawControl drawControl){
        //show the ui pane
        fileChooser.setTitle("打开一个画板文件");
        File file = fileChooser.showOpenDialog(stage);
        if (file==null)return;
        if (file.exists() && file.isFile() && file.getName().split("\\.")[1].equals(Config.FILE_SUFFIX))
            drawControl.openFile(file);
        else{
            JFXDialogLayout layout = new JFXDialogLayout();
            layout.setBody(new Label("不能打开这种类型的文件"));
            JFXAlert<Void> alert = new JFXAlert<>(stage);
            alert.setOverlayClose(true);
            alert.setAnimation(JFXAlertAnimation.CENTER_ANIMATION);
            alert.setContent(layout);
            alert.initModality(Modality.NONE);
            alert.showAndWait();
        }
    }

    public void storeFile(Stage stage, DrawControl drawControl){
        fileChooser.setTitle("保存一个画板文件");
        fileChooser.setInitialFileName("untitled"+"."+Config.FILE_SUFFIX);
        File file = fileChooser.showSaveDialog(stage);
        if (file==null)return;
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                Logger.getLogger(e.getLocalizedMessage());
            }
        }
        drawControl.storeFile(file);
    }
}
